package cj.web.uc.controllers;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.MD5Security;
import cj.utils.weixin.HttpsWenXinUtil;
import cj.web.cc.controllers.BaseController;
import cj.web.constants.MemuEnum;
import cj.web.sc.dao.AppTokenDAO;
import cj.web.sc.dao.OrderDAO;
import cj.web.uc.dao.LoginDAO;

@Path("user")
public class LoginController extends BaseController{
	
	private static final String CONFIG_CODE = "AUTH_CODE";
	
	@Autowired
	private LoginDAO loginDao;
	@Autowired
	private AppTokenDAO appTokenDao;
	@Autowired
	private OrderDAO orderDao;
	
	/**
	 * 登录页过验证
	 * @param model
	 * @param returnPage
	 * @return
	 * @throws Exception 
	 */
	@Get("loginPage")
	public String loginPageNew(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		model.add("currentTopMemu", MemuEnum.memulogin);
		String returnPage = getCookieValueByName(request,"returnPage");
		String agree = getCookieValueByName(request,"agree");//是否同意
		
		//Cookie中移除returnPage
		removeCookie(response, "agree");
		
		if(returnPage != null && returnPage.length() > 0){
			model.add("returnPage", returnPage);
		}else{
			model.add("returnPage", "/user/myPc");
		}
		
		if(agree!=null && !"".equals(agree)){
			model.add("toRegister", true);
		}else{
			model.add("toRegister", false);
		}
		
		List<Map> authCodeObj = appTokenDao.queryConfigInfo(CONFIG_CODE);
		if(authCodeObj!=null && authCodeObj.size()>0){
			int authCodeValue = Integer.parseInt(authCodeObj.get(0).get("value").toString());
			//验证码（0开，1关）
			if(authCodeValue == 0){
				model.add("authCodeFlag", true);
			}else{
				model.add("authCodeFlag", false);
			}
		}
		
		return "/views/uc/loginNew.vm";
	}
	
	/**
	 * 登录页---old
	 * @param model
	 * @param returnPage
	 * @return
	 * @throws Exception 
	 */
	@Get("loginPageTemp")
	public String loginPage(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		model.add("currentTopMemu", MemuEnum.memulogin);
		String returnPage = getCookieValueByName(request,"returnPage");
		String agree = getCookieValueByName(request,"agree");//是否同意
		
		//Cookie中移除returnPage
		removeCookie(response, "agree");
		
		if(returnPage != null && returnPage.length() > 0){
			model.add("returnPage", returnPage);
		}else{
			model.add("returnPage", "/user/myPc");
		}
		
		if(agree!=null && !"".equals(agree)){
			model.add("toRegister", true);
		}else{
			model.add("toRegister", false);
		}
		
		return "/views/uc/login.vm";
	}
	
	/**
	 * 登录方法
	 * @param phone
	 * @param pwd
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Post("login")//phone memberId
	public String login(@Param("phone")String phone,
			@Param("pwd")String pwd,HttpServletResponse response) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if(phone!=null){
			
			List<Map> reps = loginDao.getMemberByPhone(phone);
			
			if(reps.size()>0 && reps.size()==1){
				String l_pwd = reps.get(0).get("pwd").toString();
				String memberId = reps.get(0).get("id").toString();
				String sex = reps.get(0).get("sex").toString();
				if(l_pwd.equals(MD5Security.md5(pwd))){
					//密码相等
					setCookie(response, "phone", phone);//电话号码
					setCookie(response, "memberId", memberId);//用户ID
					setCookie(response, "sex", sex);//性别
					//种植的Key
					setCookie(response, "_token_", MD5Security.returnSingKey(phone+memberId+KEY_TOKEN_));//种植的Key
					//Cookie中移除returnPage
					removeCookie(response, "returnPage");
				}else{
					//密码错误
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
					jo.put("returnCode", Constants.returnObj.returnCode.code_1);
				}
				
			}else{
				//不存在此用户
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_2);
			}
			
			
		}else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 注册方法-图形验证码
	 * @param phone
	 * @param token
	 * @param pwd
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@Post("register")
	public synchronized String registerNew(@Param("phone")String phone, @Param("token")String token
			, @Param("pwd")String pwd, @Param("key")String key, HttpServletResponse response
			, HttpSession session) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		int memberId =0;
		
		//验证码判断
		boolean authCodeFlag = returnAuthCodeFlag(key, session);
		
		if(authCodeFlag){
			//图形验证码相同
			if(appTokenDao.queryToken(phone, token)>0){
				List<Map> uc = loginDao.getMemberByPhone(phone);
				if(uc.size() == 0){
					//不存在
					memberId = loginDao.register(phone,MD5Security.md5(pwd),null);
					setCookie(response, "phone", phone);//电话号码
					setCookie(response, "memberId", String.valueOf(memberId));//用户ID
					//种植的Key
					setCookie(response, "_token_", MD5Security.returnSingKey(phone+memberId+KEY_TOKEN_));//种植的Key
					appTokenDao.updateToken(phone);
				}else if(uc.size()>0){
					//存在
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
					jo.put("returnCode", Constants.returnObj.returnCode.code_1);
				}
			}
			else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			}
		}else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 判断验证码是否开启，开启状态验证图形验证码
	 * @param key			验证码
	 * @param session
	 * @return
	 */
	private boolean returnAuthCodeFlag(String key, HttpSession session){
		boolean authCodeFlag = false;
		//获取配置的验证码值
		List<Map> authCodeObj = appTokenDao.queryConfigInfo(CONFIG_CODE);
		if(authCodeObj!=null && authCodeObj.size()>0){
			int authCodeValue = Integer.parseInt(authCodeObj.get(0).get("value").toString());
			//验证码（0开，1关）
			if(authCodeValue == 0){
				//验证图形验证码
				String strCode = session.getAttribute("strCode").toString();
				authCodeFlag = (strCode!=null && key.equals(strCode));
			}else{
				//验证码判断直接逻辑为真
				authCodeFlag = true;
			}
		}else{
			//验证图形验证码
			String strCode = session.getAttribute("strCode").toString();
			authCodeFlag = (strCode!=null && key.equals(strCode));
		}
		return authCodeFlag;
	}
	
	/**
	 * 注册方法---old
	 * @param phone
	 * @param token
	 * @param pwd
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@Post("registerTemp")
	public synchronized String register(@Param("phone")String phone, @Param("token")String token
			, @Param("pwd")String pwd, HttpServletResponse response) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		int memberId =0;
		if(appTokenDao.queryToken(phone, token)>0){
			List<Map> uc = loginDao.getMemberByPhone(phone);
			if(uc.size() == 0){
				//不存在
				memberId = loginDao.register(phone,MD5Security.md5(pwd),null);
				setCookie(response, "phone", phone);//电话号码
				setCookie(response, "memberId", String.valueOf(memberId));//用户ID
				//种植的Key
				setCookie(response, "_token_", MD5Security.returnSingKey(phone+memberId+KEY_TOKEN_));//种植的Key
				appTokenDao.updateToken(phone);
			}else if(uc.size()>0){
				//存在
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_1);
			}
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 楚才用户使用协议
	 * @return
	 */
	@Get("agreeMent")
	public String agreeMent(Model model){
		model.add("currentTopMemu", MemuEnum.memulogin);
		return "/views/apply/agreement.vm";
	}
	
	@Get("agree")
	public String agree(Model model, HttpServletResponse response){
		model.add("currentTopMemu", MemuEnum.memulogin);
		setCookie(response, "agree", "agree");//电话号码
		return "r:loginPage";
	}
	
	/**
	 * 找回密码页面
	 * @return
	 */
	@Get("forgetPwdPage")
	public String forgetPwdPage(Model model){
		model.add("currentTopMemu", MemuEnum.memulogin);
		return "/views/uc/forgetPwdNew.vm";
	}
	
	/**
	 * 找回密码
	 * @param phone
	 * @param token
	 * @param pwd
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Post("forgetPwd")
	public String forgetPwd(@Param("phone")String phone, @Param("token")String token
			, @Param("pwd")String pwd, @Param("key")String key, HttpServletResponse response
			, HttpSession session) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> uc = loginDao.getMemberByPhone(phone);
		if(uc.size() == 0){
			//不存在
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_2);
		}else if(uc.size()>0){
			//存在
			//验证码判断
			boolean authCodeFlag = returnAuthCodeFlag(key, session);
			
			if(authCodeFlag){
				//图形验证码相同
				if(appTokenDao.queryToken(phone, token)>0){
					
					int memberId = Integer.parseInt(uc.get(0).get("id").toString());//userId
					
					loginDao.updateMemberId(memberId, MD5Security.md5(pwd));
					appTokenDao.updateToken(phone);
				}
				else{
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				}
			}else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			}
			
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 登出
	 * @param response
	 * @return
	 */
	@Get("logout")
	public String logout(Model model,HttpServletResponse response){
		removeCookie(response,"phone");
		removeCookie(response,"memberId");
		removeCookie(response,"_token_");
		//Cookie中移除returnPage
		removeCookie(response, "returnPage");
		return "r:my";
	}
	
	/**
	 * 登出
	 * @param response
	 * @return
	 */
	@Get("logoutPc")
	public String logoutPc(Model model,HttpServletResponse response){
		removeCookie(response,"phone");
		removeCookie(response,"memberId");
		removeCookie(response,"_token_");
		//Cookie中移除returnPage
		removeCookie(response, "returnPage");
		return "r:myPc";
	}
	
	@Get("myCode")  //登录Code
	public String myCode(Model model,@Param("code")String code, HttpServletResponse response) throws Exception{
		Map oauth2Reps = HttpsWenXinUtil.retOauth2Infor(code, APPID, APPSECRET);
		String access_token = oauth2Reps.get("access_token").toString();
		String openId = oauth2Reps.get("openid").toString();
		
//		String access_token = "5_t_0b1DfJd-miqaupR01BIoZkDZBL_FAVKk4TUW3_HTf9MQzfBzWD6tcJNVO0DSdSBmLDWVHckSPoQJOHq8xr9Q";
//		String openId = "ofwuNsyVHbXdpotCwZ_ZJLp7DSrQ";
		
		setCookie(response, "openId", openId);
		
		//---------------------判断是否存在绑定账号
		List<Map> reps = loginDao.getMemberByOpenId(openId);
		if(reps.size()>0 && reps.size()==1){
			//存在已经绑定过了得账号
			String memberId = reps.get(0).get("id").toString();
			String sex = reps.get(0).get("sex").toString();
			String phone = reps.get(0).get("phone").toString();
			
			setCookie(response, "phone", phone);//电话号码
			setCookie(response, "memberId", memberId);//用户ID
			setCookie(response, "sex", sex);//性别
			
			//种植的Key
			setCookie(response, "_token_", MD5Security.returnSingKey(phone+memberId+KEY_TOKEN_));//种植的Key
			
			//Cookie中移除returnPage
			removeCookie(response, "returnPage");
			
		}else{
			model.add("currentTopMemu", MemuEnum.memulogin);
			model.add("access_token", access_token);
			model.add("openid", openId);
			//显示绑定和注册页面
			model.add("returnPage", "/user/my");
			return "/views/uc/thirdParty/bindingPhone.vm";
		}
		
		return "r:my";
	}
	
	/**
	 * 用户中心
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@Get("my")
	public String my(Model model, HttpServletRequest request) throws Exception{
		if(isLogin(request)){
			String phone = getCookieValueByName(request, "phone");
			String memberId = getCookieValueByName(request, "memberId");
			model.add("memberId", memberId);
			model.add("phone", phone);
			model.add("isLogin", true);
		}else{
			model.add("isLogin", false);
		}
		model.add("currentTopMemu", MemuEnum.memugrzx);
		
		//--------------微信签名
		Map<String, String> config = getConfigSign(request);
		model.add("Config",config);
				
		return "/views/uc/wx/userCenter.vm";
	}
	
	/**
	 * 用户中心
	 * @param model
	 * @param request
	 * @return
	 */
	@Get("myPc")
	public String myPc(Model model, HttpServletRequest request){
		if(isLogin(request)){
			String phone = getCookieValueByName(request, "phone");
			String memberId = getCookieValueByName(request, "memberId");
			model.add("memberId", memberId);
			model.add("phone", phone);
			model.add("isLogin", true);
		}else{
			model.add("isLogin", false);
		}
		model.add("currentMemu", MemuEnum.wdbm);
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/uc/userCenter.vm";
	}
	
	private int getBuyerId(HttpServletRequest request){
    	String phone = getCookieValueByName(request, "phone");
		int buyerId = loginDao.getBuyerId(phone);
		
		return buyerId;
    }
	
	/**
	 * 关于我们
	 * @return
	 */
	@Get("aboutus")
	public String aboutUs(Model model){
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/uc/wx/aboutUs.vm";
	}
	
	/**
	 * 关于我们
	 * @return
	 */
	@Get("aboutusPc")
	public String aboutusPc(Model model, HttpServletRequest request){
		if(isLogin(request)){
			String phone = getCookieValueByName(request, "phone");
			String memberId = getCookieValueByName(request, "memberId");
			model.add("memberId", memberId);
			model.add("phone", phone);
			model.add("isLogin", true);
			
		}else{
			model.add("isLogin", false);
		}
		model.add("currentMemu", MemuEnum.gywm);
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/uc/aboutUs.vm";
	}
	
	//------------------------------------------------第三方登录——微信
	/**
	 * 第三方登录——微信
	 * @param model
	 * @param code
	 * @param state
	 * @return
	 * @throws Exception 
	 */
	@Get("thirdPartyLoginsWX")
	public synchronized String thirdPartyLoginsWX(Model model,@Param("code")String code,
			@Param("state")String state, HttpServletResponse response) throws Exception{
		Map rep = HttpsWenXinUtil.retOauth2Infor(code,KF_APPID,KF_APPSECRET);
		
//		Map rep = new HashMap();
//		rep.put("access_token", "5_t_0b1DfJd-miqaupR01BIoZkDZBL_FAVKk4TUW3_HTf9MQzfBzWD6tcJNVO0DSdSBmLDWVHckSPoQJOHq8xr9Q");
//		rep.put("openid", "oj1E80degiaY6K2dyMd5IPa5gRYE");
		
		setCookie(response, "access_token", rep.get("access_token").toString());//电话号码
		setCookie(response, "openid", rep.get("openid").toString());//用户ID
		
		List<Map> reps = loginDao.getMemberByOpenId(rep.get("openid").toString());
		
		if(reps.size()>0 && reps.size()==1){
			//存在已经绑定过了得账号
			String memberId = reps.get(0).get("id").toString();
			String sex = reps.get(0).get("sex").toString();
			String phone = reps.get(0).get("phone").toString();
			
			setCookie(response, "phone", phone);//电话号码
			setCookie(response, "memberId", memberId);//用户ID
			setCookie(response, "sex", sex);//性别
			
			//种植的Key
			setCookie(response, "_token_", MD5Security.returnSingKey(phone+memberId+KEY_TOKEN_));//种植的Key
			
			//Cookie中移除returnPage
			removeCookie(response, "returnPage");
			
			//存在账号直接去活动页面
			return "r:../game/home";
		}
		
		//显示绑定和注册页面
		return "r:bindingPhonePage";
	}
	
	/**
	 * 绑定微信页面需跳转
	 * @param model
	 * @param response
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("bindingPhonePage")
	public String bindingPhonePage(Model model, HttpServletResponse response, HttpServletRequest request) throws Exception{
		
		String access_token = getCookieValueByName(request, "access_token");
		String openid = getCookieValueByName(request, "openid");
		
		model.add("currentTopMemu", MemuEnum.memulogin);
		model.add("access_token", access_token);
		model.add("openid", openid);
		model.add("returnPage", "/game/home");
		//显示绑定和注册页面
		return "/views/uc/thirdParty/bindingPhone.vm";
	}
	
	/**
	 * 不存在手机号直接注册
	 * @param model
	 * @param phone
	 * @param token
	 * @param pwd
	 * @param openid
	 * @param access_token
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Post("bindingPhone")
	public synchronized String bindingPhone(Model model,@Param("phone")String phone, @Param("token")String token
			, @Param("pwd")String pwd,@Param("openid")String openid,@Param("access_token")String access_token
			, HttpServletResponse response, HttpServletRequest request) throws Exception{
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		int memberId =0;
		if(appTokenDao.queryToken(phone, token)>0){
			List<Map> uc = loginDao.getMemberByPhone(phone);
			if(uc.size() == 0){
				//不存在
				memberId = loginDao.register(phone,MD5Security.md5(pwd),null,openid);
				setCookie(response, "phone", phone);//电话号码
				setCookie(response, "memberId", String.valueOf(memberId));//用户ID
				//种植的Key
				setCookie(response, "_token_", MD5Security.returnSingKey(phone+memberId+KEY_TOKEN_));//种植的Key
				appTokenDao.updateToken(phone);
			}else if(uc.size()>0){
				//存在
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_1);
			}
		}else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 存在账号直接绑定
	 * @param model
	 * @param phone
	 * @param token
	 * @param pwd
	 * @param openid
	 * @param access_token
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Post("bindingPhoneExist")
	public synchronized String bindingPhoneExist(Model model,@Param("phone")String phone, @Param("pwd")String pwd
			, @Param("openid")String openid,@Param("access_token")String access_token
			, HttpServletResponse response, HttpServletRequest request) throws Exception{
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		//是否存在手机
		List<Map> uc = loginDao.getMemberByPhone(phone);
		if(uc.size() == 0){
			//不存在
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_2);
		}else if(uc.size()>0){
			
			String l_pwd = uc.get(0).get("pwd").toString();
			String memberId = uc.get(0).get("id").toString();
			String sex = uc.get(0).get("sex").toString();
			if(l_pwd.equals(MD5Security.md5(pwd))){
				//密码相等
				setCookie(response, "phone", phone);//电话号码
				setCookie(response, "memberId", memberId);//用户ID
				setCookie(response, "sex", sex);//性别
				//种植的Key
				setCookie(response, "_token_", MD5Security.returnSingKey(phone+memberId+KEY_TOKEN_));//种植的Key
				
				//存在
				loginDao.updateOpenIdByMemberId(Integer.parseInt(memberId), openid);
			}else{
				//密码错误
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_1);
			}
		}
		
		return "@" + jo.toString();
	}
}